<template>
  <div ref="box" class="box">
    <div class="left">
      <el-header class="editor-header">
        <el-button style="border: 1px solid #000;color: #000;" @click="back">返回</el-button>
        <el-button style="border: 1px solid #fff;color: #000;">
          <i class="el-icon-time time-memory"> {{ timeLimit }} Sec</i>
          <i class="el-icon-cpu time-memory" style="margin-left: 30px;"> {{ memoryLimit }} MB</i>
        </el-button>
      </el-header>
      <el-dropdown v-if="contestId" trigger="click">
        <el-button style="border: 1px solid #848484;font-size: 20px;margin-left: 30px;">
          {{ String.fromCharCode(num+65) }}
          <i class="el-icon-arrow-down el-icon--right" />
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item
            v-for="item in contestProblem"
            :key="item.num"
            class="dropdown-problem"
            @click.native="changeProblem(item.problemId)"
          >
            {{ String.fromCharCode(item.num+65) + "：" + item.title }}
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <p style="display: inline-block;font-size: 25px;margin: 10px 0 10px 30px;">{{ problemTitle }}</p>
      <p class="mut-title">Description</p>
      <mavon-editor
        :value="mavonDescription"
        class="mavon-editor"
        :subfield="false"
        :default-open="'preview'"
        :editable="false"
        :toolbars-flag="false"
        :ishljs="true"
      />
      <p class="mut-title">Input</p>
      <mavon-editor
        :value="mavonInput"
        class="mavon-editor"
        :subfield="false"
        :default-open="'preview'"
        :editable="false"
        :toolbars-flag="false"
        :ishljs="true"
      />
      <p class="mut-title">Output</p>
      <mavon-editor
        :value="mavonOutput"
        class="mavon-editor"
        :subfield="false"
        :default-open="'preview'"
        :editable="false"
        :toolbars-flag="false"
        :ishljs="true"
      />
      <p class="mut-title">Sample Input</p>
      <mavon-editor
        :value="mavonSampleInput"
        class="mavon-editor"
        :subfield="false"
        :default-open="'preview'"
        :editable="false"
        :toolbars-flag="false"
        :ishljs="true"
      />
      <p class="mut-title">Sample Output</p>
      <mavon-editor
        :value="mavonSampleOutput"
        class="mavon-editor"
        :subfield="false"
        :default-open="'preview'"
        :editable="false"
        :toolbars-flag="false"
        :ishljs="true"
      />
      <p class="mut-title">Tips</p>
      <mavon-editor
        :value="mavonTips"
        class="mavon-editor"
        :subfield="false"
        :default-open="'preview'"
        :editable="false"
        :toolbars-flag="false"
        :ishljs="true"
      />
    </div>
    <div class="right">
      <el-header class="editor-header" style="background-color: #3B3B3B;">
        <el-button class="submit-btn" @click="submit_code">提交</el-button>
        <el-dialog
          title="提交结果"
          :visible.sync="dialogSubmitVisible"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          top="2vh"
          style="line-height: 20px;"
          width="55%"
        >
          <el-table
            v-loading="submit_loading"
            element-loading-background="#fff"
            element-loading-text="评测中..."
            :data="gridData"
            style="margin-bottom: 20px;"
          >
            <el-table-column property="judgetime" label="提交时间" />
            <el-table-column property="result" label="运行结果">
              <template slot-scope="scope">
                <div :style="{color: resultMap[scope.row.result].color,fontSize: 17+'px',fontWeight: 'bold'}">
                  {{ resultMap[scope.row.result].result }}
                </div>
              </template>
            </el-table-column>
            <el-table-column property="time" label="消耗时间">
              <template slot-scope="scope">{{ scope.row.time }} ms</template>
            </el-table-column>
            <el-table-column property="memory" label="消耗内存">
              <template slot-scope="scope">{{ scope.row.memory }} kb</template>
            </el-table-column>
            <el-table-column property="language" label="编译器">
              <template slot-scope="scope">{{ showLanguage(scope.row.language).label }}</template>
            </el-table-column>
          </el-table>
          <div v-if="!submit_loading">
            <p style="margin: 5px 0;font-size: 16px;">提交代码</p>
            <MonacoEditor
              v-model="gridData[0].source"
              :language="showLanguage(gridData[0].language).value"
              :options="submit_options"
              theme="vs-dark"
              style="height: 250px;overflow:hidden;margin-bottom: 20px;"
            />
            <p style="margin: 5px 0;font-size: 16px;">编译信息</p>
            <el-input
              :value="gridData[0].runtimeInfo || gridData[0].compileInfo"
              type="textarea"
              readonly
              :autosize="{ minRows: 4, maxRows: 8}"
            />
          </div>
        </el-dialog>
        <el-select v-model="selectLanguage" style="width:100px;" placeholder="请选择" class="select-language">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-button class="submit-records" @click="listResult">提交记录</el-button>
        <el-dialog title="运行记录" :visible.sync="dialogRunVisible" top="2vh" style="line-height: 20px;" width="70%">
          <el-table :data="gridData">
            <el-table-column type="expand">
              <template slot-scope="props">
                <p style="margin: 5px 0;font-size: 16px;">提交代码</p>
                <MonacoEditor
                  v-model="props.row.source"
                  :language="showLanguage(props.row.language).value"
                  :options="submit_options"
                  theme="vs-dark"
                  style="height: 250px;margin-bottom: 20px;"
                />
                <p style="margin: 5px 0;font-size: 16px;">编译信息</p>
                <el-input
                  :value="props.row.runtimeInfo || props.row.compileInfo"
                  type="textarea"
                  readonly
                  :autosize="{ minRows: 4, maxRows: 8}"
                />
              </template>
            </el-table-column>
            <el-table-column property="judgetime" label="提交时间" />
            <el-table-column property="result" label="运行结果" width="270px">
              <template slot-scope="scope">
                <div :style="{color: resultMap[scope.row.result].color,fontSize: 18+'px',fontWeight: 'bold'}">
                  {{ resultMap[scope.row.result].result }}
                </div>
              </template>
            </el-table-column>
            <el-table-column property="time" label="消耗时间">
              <template slot-scope="scope">{{ scope.row.time }} ms</template>
            </el-table-column>
            <el-table-column property="memory" label="消耗内存">
              <template slot-scope="scope">{{ scope.row.memory }} kb</template>
            </el-table-column>
            <el-table-column property="language" label="编译器">
              <template slot-scope="scope">
                {{ showLanguage(scope.row.language).label }}
              </template>
            </el-table-column>
          </el-table>
        </el-dialog>
      </el-header>
      <!--右侧div内容-->
      <MonacoEditor v-model="code" class="monaco-editor" :language="selectLanguage" theme="vs-dark" />
    </div>
  </div>
</template>

<script>
import MonacoEditor from 'vue-monaco'
import { languageOptions, resultMap } from '@/utils/global'
import { mavonEditor } from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
import { getProblemById } from '@/api/problem'
import { getUserId } from '@/utils/auth'
import { loginMessage } from '@/utils/login-message'
import { insertSolution, listResult, resultBySolutionId, updateSubmitProblem } from '@/api/solution'
import { Message } from 'element-ui'

export default {
  components: {
    MonacoEditor,
    mavonEditor
  },
  data() {
    return {
      gridData: [{
        judgetime: '2021-01-01 13:23:43',
        result: '4',
        time: '1000',
        memory: '1000',
        language: '0',
        source: '',
        runtimeInfo: '',
        compileInfo: ''
      }],
      submit_loading: false,
      options: languageOptions,
      dialogRunVisible: false,
      dialogSubmitVisible: false,
      selectLanguage: 'c',
      submit_options: {
        readOnly: true
      },
      num: -1,
      problemId: '',
      contestId: '',
      problemTitle: '',
      timeLimit: '',
      memoryLimit: '',
      mavonDescription: '',
      mavonInput: '',
      mavonOutput: '',
      mavonSampleInput: '',
      mavonSampleOutput: '',
      mavonTips: '',
      code: '#include <stdio.h>\n' +
        'int main(){\n' +
        '    int a,b;\n' +
        '    while(scanf("%d %d",&a, &b) != EOF)\n' +
        '        printf("%d\\n",a+b);\n' +
        '    return 0;\n' +
        '}',
      source: '',
      timer: '',
      resultMap: resultMap,
      contestProblem: [{ problemId: 0, num: 0, title: '' }]
    }
  },
  created() {
    if (this.$route.query.problemId === undefined) {
      this.$message.warning('不要乱输入')
      this.$router.back()
    } else {
      if (this.$route.query.contestId !== undefined) {
        this.contestId = this.$route.query.contestId
      }
      this.problemId = this.$route.query.problemId
      this.getProblemById()
    }
  },
  methods: {
    showLanguage(item) {
      return this.options.find(t => t.num === Number(item))
    },
    changeProblem(problemId) {
      this.problemId = problemId
      this.getProblemById()
    },
    getProblemById() {
      getProblemById({ problemId: this.problemId, contestId: this.contestId })
        .then(res => {
          this.problemTitle = res.data.title
          this.problemId = res.data.problemId
          this.timeLimit = res.data.timeLimit
          this.memoryLimit = res.data.memoryLimit
          this.mavonDescription = res.data.description
          this.mavonInput = res.data.input
          this.mavonOutput = res.data.output
          this.mavonSampleInput = res.data.sampleInput
          this.mavonSampleOutput = res.data.sampleOutput
          this.mavonTips = res.data.hint
          this.contestProblem = res.data.contestProblem
          this.num = this.contestProblem.find(t => t.problemId === Number(this.problemId)).num
          const language = res.data.language
          let i = 0
          const languageOptions = []
          while (i < 10) {
            if (((1 << i) & language) !== 0) {
              languageOptions.push(this.options.find(t => t.num === i))
            }
            i++
          }
          this.selectLanguage = languageOptions[0].value
          this.gridData[0].language = languageOptions[0].num
          this.options = languageOptions
        }).catch(err => {
          if (err.code === 'A0403') {
            this.$router.back()
          }
        })
    },
    back() {
      this.$router.go(-1)
    },
    listResult() {
      if (loginMessage()) {
        return
      }
      listResult({
        userId: getUserId(),
        problemId: this.problemId,
        contestId: this.contestId
      }).then(res => {
        if (res.data.length < 1) {
          Message.success({ showClose: true, message: '没有提交记录哦，先提交试试吧！' })
          return
        }
        this.gridData = res.data
        this.dialogRunVisible = true
      })
    },
    submit_code() {
      // 登录判断
      if (loginMessage()) {
        return
      }
      let solutionId = 0
      this.dialogSubmitVisible = true
      this.submit_loading = true
      const formData = new FormData()
      formData.set('problemId', this.problemId)
      formData.set('userId', getUserId())
      formData.set('source', this.code)
      formData.set('contestId', this.contestId)
      formData.set('num', this.num)
      formData.set('language', this.options.find(t => t.value === this.selectLanguage).num)
      insertSolution(formData).then(res => {
        solutionId = res.data
        let i = 0
        if (solutionId === 0) {
          Message.error({ showClose: true, message: '出现未知错误，请稍后再试！' })
          updateSubmitProblem({ problemId: this.problemId })
          this.dialogSubmitVisible = false
          this.submit_loading = false
          return
        }
        this.timer = setInterval(() => {
          setTimeout(() => {
            resultBySolutionId({ solutionId: solutionId }).then(res => {
              if (res.data[0].result > 3) {
                this.gridData = res.data
                this.source = res.data[0].source
                this.submit_loading = false
                clearInterval(this.timer)
                updateSubmitProblem({ problemId: this.problemId })
              }
            }).catch(() => {
              clearInterval(this.timer)
              updateSubmitProblem({ problemId: this.problemId })
              this.dialogSubmitVisible = false
              this.submit_loading = false
            })
            i++
            if (i > 13) {
              Message.error({ showClose: true, message: '服务超时，请稍后再试！' })
              clearInterval(this.timer)
              updateSubmitProblem({ problemId: this.problemId })
              this.dialogSubmitVisible = false
              this.submit_loading = false
            }
          }, 0)
        }, 1000)
      }).catch(() => {
        this.dialogSubmitVisible = false
        this.submit_loading = false
        updateSubmitProblem({ problemId: this.problemId })
      })
    }
  }
}
</script>

<style scoped>
.mavon-editor {
  width: calc(100% - 30px);
  margin: 0 0 0 30px;
}

.monaco-editor {
  width: 100%;
  height: 100%;
}

::v-deep .el-textarea__inner {
  background-color: #e5e5e5;
  color: #1c1c1c;
}

.submit-records {
  position: absolute;
  top: 10px;
  right: 20px;
  background-color: #6c757d;
  border: 1px solid #6c757d;
  color: #fff;
}

.submit-records:hover {
  background-color: #636b72;
}

.select-language {
  position: absolute;
  right: 130px;
}

.mut-title {
  font-size: 20px;
  font-weight: bolder;
  margin: 10px 0 10px 30px;
}

.time-memory {
  font-size: 17px;
  color: #787878;
  font-weight: bold;
  font-style: italic;
}

.editor-header {
  line-height: 60px;
  padding: 0 30px 0 30px;
}

.submit-btn {
  color: #0acf97;
  border: 1px solid #0acf97;
  background-color: #fff0
}

.submit-btn:hover {
  color: #fff;
  background-color: #0acf97
}

.dropdown-problem {
  color: #000;
  font-size: 18px;
}

.v-note-wrapper {
  min-height: 0px;
}

/* 拖拽相关样式 */
/*包围div样式*/
.box {
  width: 100%;
  height: 100%;
  margin: 0;
  overflow: hidden;
  box-shadow: -1px 9px 10px 3px rgba(0, 0, 0, 0.11);
}

/*左侧div样式*/
.left {
  width: calc(50%); /*左侧初始化宽度*/
  height: 100%;
  background: #FFFFFF;
  float: left;
  overflow: auto;
}

/*右侧div'样式*/
.right {
  float: left;
  width: 50%; /*右侧初始化宽度*/
  height: 100%;
  background: #fff;
  box-shadow: -1px 1px 1px 1px rgba(0, 0, 0, 0.11);
}

</style>
